package com.pureman.androidapp.socket;

import com.pureman.androidapp.utils.LogUtils;

import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


/**
 * Created by Administrator on 2016/6/24 0024.
 * <p/>
 * UDP协议连接
 */
public class UDPUtil extends Thread {

    //    private static final String HOST = "192.168.1.255";
    private static final String HOST = "255.255.255.255";

    private InetAddress address;
    private DatagramSocket socket;

    public void setReconnect(boolean reconnect) {
        this.reconnect = reconnect;
    }

    private boolean reconnect = false;

    public static UDPUtil getInstance() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static UDPUtil instance = new UDPUtil();
    }

    public UDPUtil() {
        start();
    }

    @Override
    public void run() {
        while (true) {
            while (this.reconnect) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    socket = new DatagramSocket();
                    address = InetAddress.getByName(HOST);
                    socket.setSoTimeout(ConnectConfig.TIME_OUT);

                    LogUtils.i("udp scoket......");

                    send(ConnectConfig.WIFI_SEND_INIT);
                    receive();
                } catch (ConnectException e) {//服务器拒绝连接、服务器没有启动、（超出队列数，拒绝连接）
                    e.printStackTrace();
                    LogUtils.i("ConnectException-->" + e.getMessage());
                } catch (BindException e) {//Socket对象无法与制定的本地IP地址或端口绑定
                    e.printStackTrace();
                    LogUtils.i("BindException-->" + e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    LogUtils.i("IOException-->" + e.getMessage());
                }
            }
        }
    }

//    public void connect() {
//        start();
//    }

    public boolean connectionStatus() {
//        return socket == null ? false : (socket.isConnected() && !socket.isClosed());
        return socket == null ? false : (socket.isBound());
    }

    public void send(byte[] bytes) {
        LogUtils.i("udp send-len->" + bytes.length);

//        LogUtils.i("bytes-->" + bytes[0]);
//        LogUtils.i("bytes-->" + bytes[1]);
//        LogUtils.i("bytes-->" + bytes[2]);
//        LogUtils.i("bytes-->" + bytes[3]);
//        LogUtils.i("bytes-->" + bytes[4]);
//        LogUtils.i("bytes-->" + bytes[5]);
//        LogUtils.i("bytes-->" + bytes[6]);
//        LogUtils.i("bytes-->" + bytes[7]);
//        LogUtils.i("bytes-->" + bytes[8]);
//        LogUtils.i("bytes-->" + bytes[9]);
//        LogUtils.i("bytes-->" + bytes[10]);

//        try {
//            LogUtils.i("udp send-content->" + new String(bytes, "ISO-8859-1"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

        try {
            Thread.sleep(ConnectConfig.SLEEP);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, ConnectConfig.PORT);
        try {
            socket.send(packet);
//            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void receive() {
        try {
            Thread.sleep(ConnectConfig.SLEEP);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        byte[] bytes = new byte[128];
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
        try {
            socket.receive(packet);
//            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String receive = new String(packet.getData(), 0, packet.getLength());
        LogUtils.i("udp receive-->" + receive);

        // 解析发送方传递的消息，并打印
        String getMes = new String(bytes, 0, packet.getLength());
        LogUtils.i("对方发送的消息：" + getMes);

//        // 通过数据报得到发送方的IP和端口号，并打印
//        InetAddress sendIP = packet.getAddress();
//        int sendPort = packet.getPort();
//        LogUtils.i("对方的IP地址是：" + sendIP.getHostAddress());
//        LogUtils.i("对方的端口号是：" + sendPort);
    }

    public void close() {
//        if (socket != null && socket.isConnected()) {
        if (connectionStatus()) {
            socket.close();
        }
    }
}
